<template>
  <div class="generality-topic-wrapper" v-loading="isLoading">
    <div class="common-wrong-search" v-if="from">
      <transition-group name="list">
        <div
          class="selected-student"
          key="selected-student"
          v-if="knowledgeStore.selectedStudent?.length"
        >
          <el-popover placement="right" :width="400" trigger="hover">
            <template #reference>
              <el-tag closable type="info" @close="closeStudent">
                已选{{ knowledgeStore.selectedStudent?.length }}位学生
              </el-tag>
            </template>
            <a-table
              :dataSource="knowledgeStore.studentSituationData"
              :columns
              rowKey="student_id"
              :rowSelection="{
                selectedRowKeys: selectedRowKeys,
                onChange: handleSelectionChange,
                columnWidth: '3%'
              }"
              :locale="{
                emptyText: '暂无数据',
                cancelSort: '点击取消排序',
                triggerAsc: '点击升序',
                triggerDesc: '点击降序'
              }"
              :pagination="false"
              :scroll="{ y: '73vh' }"
            >
            </a-table>
          </el-popover>
        </div>

        <div class="search-wrapper" key="search-wrapper">
          <el-popover v-if="search.taskId" placement="bottom-start">
            <p>{{ search.taskName }}</p>
            <template #reference>
              <div class="title">
                <div class="title-wrap">
                  <p class="name">{{ search.taskName }}</p>
                  <el-icon class="icon" @click="clearSearch('title')">
                    <Close />
                  </el-icon>
                </div>
              </div>
            </template>
          </el-popover>
          <el-popover
            v-if="from === 'common-wrong'"
            placement="bottom-start"
            popper-class="right-rate-popover"
            trigger="click"
            @hide="hideRateSearch"
          >
            <div class="right-rate">
              <p class="name">正确率</p>
              <div class="input-box">
                <el-input-number
                  placeholder="最低"
                  :controls="false"
                  :min="0"
                  v-model="search.cacheLowRate"
                ></el-input-number>
                <span class="separator">—</span>
                <el-input-number
                  placeholder="最高"
                  :controls="false"
                  :max="100"
                  v-model="search.cacheHighRate"
                ></el-input-number
                >%
              </div>
            </div>
            <template #reference>
              <label
                >正确率：{{ formatRate(search.low_rate, true) }}-{{
                  formatRate(search.high_rate, true)
                }}
                <el-icon class="icon"> <ArrowDown /> </el-icon
              ></label>
            </template>
          </el-popover>
        </div>
        <el-select
          v-if="from === 'common-wrong'"
          multiple
          collapse-tags
          v-model="search.category"
          class="type-select"
          key="type-select"
          placeholder="题型选择"
          @change="selectType"
        >
          <el-option
            v-for="item in questionTypes"
            :key="item.data.id"
            :label="item.data.name"
            :value="item.data.id"
        /></el-select>
        <span key="total"
          >共<span class="total">{{ total }}</span
          >道题目</span
        >
      </transition-group>
    </div>
    <div
      class="generality-topic"
      ref="scrollableDivRef"
      @scroll="handleScroll"
      v-if="topicList.length"
    >
      <template v-for="(item, index) in renderList" :key="index">
        <topic
          :topicData="item.question"
          :showTopicParser="item.showTopicParser"
        >
          <template #topic-head>
            <div class="topic-head">
              <div class="label-arr">
                <div class="label">
                  <span v-if="from === 'common-wrong'">{{ index + 1 }}、</span
                  >{{ questionTypeMap[item.question.type] }}
                </div>
                <div class="divide"></div>
                <div class="label">
                  {{ difficultyMap[item.question.difficulty] }}
                </div>
                <div class="divide"></div>
                <div class="label">ID：{{ item.question.id }}</div>
              </div>
            </div>
          </template>
          <template #topic-foot>
            <div class="topic-foot">
              <div class="knowledge" v-if="item.question?.keypoint?.length">
                知识点：<span
                  class="knowledge-name"
                  v-for="(kp, index) in item.question.keypoint"
                  :key="index"
                  >{{ kp.name }}</span
                >
              </div>
              <div class="more" :class="{ 'flex-end': !from }">
                <p
                  v-if="from === 'common-wrong'"
                  class="statistics-tip"
                  @click="switchStatistics(index, item)"
                >
                  <span>{{ item.members }}人做过</span>
                  <span>班级正确率{{ formatRate(item.score_rate) }}</span>
                  <span>年级平均{{ formatRate(item.grade_score_rate) }}</span>
                  <el-icon
                    v-if="item.origin_from === 4 && search.taskId"
                    :class="{ expanded: item.showStatistics }"
                  >
                    <ArrowRight />
                  </el-icon>
                </p>
                <el-popover
                  v-else-if="from === 'personal-wrong'"
                  popper-class="answer-record-popover"
                  :show-arrow="false"
                  placement="bottom-start"
                >
                  <ul class="record-list">
                    <li
                      class="list-item"
                      v-for="item1 in item.reply_record || []"
                      :key="item1.task_id"
                    >
                      {{
                        dayjs(item1.task_time * 1000).format('YYYY-MM-DD')
                      }}：<span
                        :style="{
                          color: getColor(item1.src_score, item1.score)
                        }"
                      >
                        <template
                          v-if="
                            getRecordAnswer(
                              item.question,
                              item1.answer,
                              item1.task_id
                            )
                          "
                          >{{
                            getRecordAnswer(
                              item.question,
                              item1.answer,
                              item1.task_id
                            )
                          }}</template
                        >
                        <template v-else> {{ item1.score }}分</template></span
                      >
                      <el-icon v-if="item1.urls">
                        <Picture />
                      </el-icon>
                    </li>
                  </ul>
                  <template #reference>
                    <p
                      class="record-tip"
                      @click="showRecord(item.reply_record, item.question)"
                    >
                      <span
                        >作答记录({{ (item.reply_record || []).length }})</span
                      >
                      <span v-if="item.reply_record?.length"
                        >{{
                          dayjs(item.reply_record[0].task_time * 1000).format(
                            'YYYY-MM-DD'
                          )
                        }}：
                        <span
                          :style="{
                            color: getColor(
                              item.reply_record[0].src_score,
                              item.reply_record[0].score
                            )
                          }"
                          ><template
                            v-if="
                              getRecordAnswer(
                                item.question,
                                item.reply_record[0].answer,
                                item.reply_record[0].task_id
                              )
                            "
                            >{{
                              getRecordAnswer(
                                item.question,
                                item.reply_record[0].answer,
                                item.reply_record[0].task_id
                              )
                            }}</template
                          >
                          <template v-else>
                            {{ item.reply_record[0].score }}分</template
                          >
                        </span>
                      </span>
                      <el-icon v-if="item.reply_record?.[0]?.urls">
                        <Picture />
                      </el-icon>
                      <span
                        >题目总分：{{
                          item.reply_record[0].src_score || 0
                        }}分</span
                      >
                    </p>
                  </template>
                </el-popover>
                <div class="btn-group">
                  <div
                    class="basket-btn"
                    :class="{
                      'remove-btn': isInBasket(item.question),
                      disabled: isPushing
                    }"
                    @click="
                      isInBasket(item.question)
                        ? onRemoveBasket(item.question)
                        : onAddBasket(item.question)
                    "
                  >
                    {{ isInBasket(item.question) ? '移出' : '加入' }}选题篮
                  </div>
                  <div class="action-btn" @click="handleCheckParse(index)">
                    <label class="analysis-icon icon"></label>
                    <span
                      >{{ item.showTopicParser ? '收起' : '查看' }}解析</span
                    >
                  </div>
                </div>
              </div>
              <div
                class="expand-box flex"
                v-if="item.showStatistics"
                v-loading="item.loading"
              >
                <div class="process-box">
                  <ProcessList
                    :process-list="item.processList"
                    :sum="item.sum"
                  />
                </div>
                <div class="student-box">
                  <div
                    class="answer-box"
                    v-for="(answer, index) in item.processList"
                    :key="index"
                  >
                    <div class="flex">
                      <template v-if="answer.statistics_type === 5">
                        <img class="index-img" :src="answer.text" />

                        &nbsp; ({{ answer.list?.length || 0 }})人
                      </template>

                      <span
                        v-else
                        :class="answer.isCorrect && 'correct-answer'"
                      >
                        {{ answer.text }}
                        &nbsp; ({{ answer.list?.length || 0 }})人
                      </span>
                      <span
                        v-if="answer.statistics_type !== 5"
                        class="correct-answer"
                      >
                        &nbsp;&nbsp;{{ answer.isCorrect ? '正答' : '' }}
                      </span>
                    </div>
                    <div class="student-list flex">
                      <div
                        class="student-item flex"
                        v-for="(student, index) in answer.list"
                        :key="index"
                      >
                        <div class="student-name text-ellipsis">
                          {{ student.student_name }}
                        </div>
                        {{ student.completed_at }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </topic>
        <template v-if="item.pushingList.length && isPushing">
          <topic
            class="jyfs-question"
            v-for="(question1, index1) in item.pushingList"
            v-loading="question1.loading"
            :key="index1"
            :topicData="question1.question"
            :showTopicParser="question1.showTopicParser"
          >
            <template #topic-head>
              <div class="topic-head">
                <div class="label-arr">
                  <div class="label jyfs-label">举一反三{{ index1 + 1 }}</div>
                  <div class="divide"></div>
                  <div class="label">
                    {{ questionTypeMap[question1.question.type] }}
                  </div>
                  <div class="divide"></div>
                  <div class="label">
                    {{ difficultyMap[question1.question.difficulty] }}
                  </div>
                  <div class="divide"></div>
                  <div class="label">ID：{{ question1.question.id }}</div>
                </div>
              </div>
            </template>
            <template #topic-foot>
              <div class="topic-foot">
                <div
                  class="knowledge"
                  v-if="question1.question?.keypoint?.length"
                >
                  知识点：<span
                    class="knowledge-name"
                    v-for="(kp, index) in question1.question.keypoint"
                    :key="index"
                    >{{ kp.name }}</span
                  >
                </div>
                <div class="more flex-end">
                  <div class="btn-group">
                    <button
                      class="basket-btn"
                      :class="{ 'remove-btn': question1.isSelected }"
                      @click="selectQuestion(index, index1)"
                    >
                      {{ question1.isSelected ? '已选入' : '选入' }}
                    </button>
                    <div
                      class="action-btn"
                      @click="switchJyfsQuestionAna(index, index1)"
                    >
                      <label class="icon"></label>
                      <span
                        >{{
                          question1.showTopicParser ? '收起' : '查看'
                        }}解析</span
                      >
                    </div>
                    <!-- <div
                      class="action-btn"
                      @click="switchAnother(question1, index, index1)"
                    >
                      <el-icon class="icon">
                        <RefreshRight />
                      </el-icon>换一道
                    </div> -->
                  </div>
                </div>
                <div v-if="question1.showStatistics" class="statistics">
                  统计
                </div>
              </div>
            </template>
          </topic>
        </template>
      </template>
    </div>
    <el-empty v-else />
    <div class="btn-box" v-if="isPushing">
      <button class="btn cancel-btn" @click="emits('close-pushing')">
        取消
      </button>
      <button class="btn save-btn" @click="saveSimilarQuestion">
        确认保存
      </button>
    </div>
    <el-drawer v-model="drawerVisible" title="作答记录" class="record-drawer">
      <ul class="record">
        <li
          class="record-item"
          v-for="item in currentRecord"
          :key="item.task_id"
        >
          <p class="info">
            <span :style="{ color: getColor(item.src_score, item.score) }">
              <span>{{
                dayjs(item.task_time * 1000).format('YYYY-MM-DD')
              }}</span>
              <span class="score">
                <template
                  v-if="
                    getRecordAnswer(
                      currentRecord.question,
                      item.answer,
                      item.task_id
                    )
                  "
                  >{{
                    getRecordAnswer(
                      currentRecord.question,
                      item.answer,
                      item.task_id
                    )
                  }}</template
                >
                <template v-else> {{ item.score }}分</template></span
              ></span
            >
            <span>{{ item.task_name }}</span>
          </p>
          <template v-if="item.urls">
            <img v-for="img in item.urls" :src="img" :key="img" />
          </template>
        </li>
      </ul>
    </el-drawer>
  </div>
</template>

<script setup>
import {
  ref,
  watch,
  reactive,
  computed,
  onMounted,
  onBeforeMount,
  h
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useTaskStore, useAuthStore, useKnowledgeStore } from '@/stores'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

import topic from '@/components/rb-topic/Topic.vue'
import ProcessList from '@/views/assignment/components/ProcessList.vue'
import { Close, Picture, ArrowRight, ArrowDown } from '@element-plus/icons-vue'

import { throttle } from 'lodash'
import { rankMap } from '@/views/assignment/util'
import { questionTypeMap } from '@/constants'
import { difficultyMap } from '../data'
import {
  getQuestionType,
  getJyfsQustions,
  getXkwSimilarQuestions
} from '@/apis/target-boost/index'
import { getResponseStatistics } from '@/apis/assignment'

const taskStore = useTaskStore()
const authStore = useAuthStore()
const knowledgeStore = useKnowledgeStore()
const router = useRouter()
const route = useRoute()

const emits = defineEmits([
  'generalityNextPage',
  'refresh-common-list',
  'close-pushing',
  'get-generality-topic'
])

const props = defineProps({
  topicData: {
    type: Array,
    default: () => []
  },
  total: {
    type: Number,
    default: 0
  },
  from: {
    type: String,
    default: ''
  },
  isPushing: {
    type: Boolean,
    default: false
  },
  isLoading: {
    type: Boolean,
    default: false
  }
})

const closeStudent = () => {
  knowledgeStore.selectedStudent = []
}

const selectedRowKeys = ref([])

const handleSelectionChange = (keys, selectedRows) => {
  console.log(selectedRows)
  selectedRowKeys.value = keys
  knowledgeStore.setSelectedStudent(selectedRows)
}
watch(
  () => knowledgeStore.selectedStudent,
  async () => {
    selectedRowKeys.value = knowledgeStore.selectedStudent.map(
      item => item.student_id
    )
    handleSelectionChange(selectedRowKeys.value, knowledgeStore.selectedStudent)
  },
  {
    immediate: true,
    deep: true
  }
)

const columns = [
  {
    title: '学生',
    dataIndex: 'student_name',
    key: 'student_name',
    align: 'center',
    width: '20%'
  },
  {
    title: '综合(题目去重)',
    dataIndex: 'rate',
    key: 'rate',
    align: 'center',
    width: '20%',
    customRender: ({ text, record }) => {
      if (record.rate === 0 && record.question_count === 0) return '--'
      return h('div', {}, [
        h('span', {}, text ? `${(text * 100).toFixed(2)}%` : '0.00%'),
        h(
          'span',
          {
            style: {
              'margin-left': '10px'
            }
          },
          `${record.question_count}题`
        )
      ])
    },
    sorter: (a, b) => a.rate - b.rate
  }
]

// 加载首次数据
onBeforeMount(() => {
  if (!props.topicData.length) {
    emits('get-generality-topic')
  }
})

const scrollableDivRef = ref()

const topicList = ref([])

const onAddBasket = question => {
  const params = {
    topic_id: question.id,
    source: 1,
    topic_type: question.type,
    subject_id: question.subject,
    question_detail: question,
    is_similar: 0,
    relation_id: 0
  }
  taskStore.setTaskList(params)
}

const onRemoveBasket = (item, isSimilar) => {
  if (props.isPushing && !isSimilar) return
  taskStore.deleteTopicById([item.id])
  resetCommonList()
}

const isInBasket = question => {
  return taskStore.taskList.find(item => item.topic_id === question?.id)
}

watch(
  () => props.topicData,
  newValue => {
    // if (newValue.length == 0) {
    //   return
    // }
    let newTopicArr = JSON.parse(JSON.stringify(newValue))
    newTopicArr.forEach(element => {
      if (element.showTopicParser == undefined) {
        element.showTopicParser = false
      }
    })
    topicList.value = newTopicArr.map(item => {
      return {
        showStatistics: false, // 是否展示解析
        loading: false,
        pushingList: [], // 举一反三关联列表
        processList: [], // 作答列表
        sum: 0,
        ...item
      }
    })
  },
  {
    deep: true,
    immediate: true
  }
)

function handleCheckParse(index) {
  topicList.value[index].showTopicParser =
    !topicList.value[index].showTopicParser
}

const handleScroll = throttle(function () {
  if (
    scrollableDivRef.value.scrollTop +
      scrollableDivRef.value.clientHeight +
      10 >=
    scrollableDivRef.value.scrollHeight
  ) {
    emits('generalityNextPage', handleParams())
  }
}, 500)

const switchStatistics = async (index, item) => {
  if (item.origin_from !== 4 || !search.taskId) return
  topicList.value[index].showStatistics = !topicList.value[index].showStatistics
  if (topicList.value[index].showStatistics) {
    topicList.value[index].loading = true
    await getResponseStatisticsInfo(item)
  }
  topicList.value[index].loading = false
}

// 获取统计数据
const getResponseStatisticsInfo = async curQuestionInfo => {
  curQuestionInfo.processList = []
  let realQuestion = curQuestionInfo.question
  // 题目类型
  const res = await getResponseStatistics({
    task_id: search.taskId,
    class_id: route.query.class_id,
    question_id: curQuestionInfo.question.id,
    item_type: 1
  })

  let { correct_answer } = realQuestion
  correct_answer = correct_answer ? correct_answer.join('') : ''

  const data = res.data?.result || {}
  const list = Object.keys(data)
  curQuestionInfo.sum = res.data?.student_count || 0
  curQuestionInfo.processList = list.map(key => {
    let param = {
      key,
      isCorrect: false,
      list: data[key].list || [],
      statistics_type: res.data.statistics_type
    }
    switch (param.statistics_type) {
      case 1:
      case 2:
      case 3:
        param.text = key
        param.isCorrect = key == correct_answer
        break
      case 4:
        param.text = key === 'correct' ? '选: 对/T' : '选: 错/F'
        param.isCorrect =
          (key === 'correct' && correct_answer === 0) ||
          (key === 'wrong' && correct_answer === 1)
        break
      case 5:
        param.text = rankMap[key]
    }
    return param
  })
}

// 查询
const search = reactive({
  low_rate: 0,
  high_rate: 100,
  cacheLowRate: 0,
  cacheHighRate: 100,
  taskName: route.query.task_name || '',
  taskId: route.query.task_id || '',
  originTaskId: route.query.origin_task_id || '',
  category: [0]
})

const hideRateSearch = () => {
  if (!search.cacheLowRate) search.cacheLowRate = 0
  if (!search.cacheHighRate) search.cacheHighRate = 100
  search.low_rate = search.cacheLowRate
  search.high_rate = search.cacheHighRate
}

const selectType = types => {
  if (types.length > 1) {
    if (types[0] === 0) {
      search.category = types.slice(1)
    } else if (types.at(-1) === 0) {
      search.category = [0]
    }
  } else {
    search.category = types
  }
}

// const changeTypeVisible = visible => {
//   console.log(visible)

//   if (!visible) {
//     refreshList()
//   }
// }

const formatRate = (rate, isMultiple = false) => {
  const num = isMultiple ? rate : rate * 100
  return parseFloat(num.toFixed(2)) + '%'
}
const clearSearch = type => {
  if (type === 'title') {
    search.taskId = ''
    search.taskName = ''
    search.originTaskId = ''
  }
  refreshList()
}

// 获取题型枚举
const questionTypes = ref([])
const getQuestionTypeFn = async () => {
  const params = {
    subject_id: authStore.nowGlobalSubjectId,
    stage_id: authStore.nowGlobalStageId
  }
  const res = await getQuestionType(params)
  if (res.data) {
    questionTypes.value = [{ data: { id: 0, name: '全部' } }, ...res.data]
  } else {
    questionTypes.value = [{ data: { id: 0, name: '全部' } }]
  }
}

function getAllIds(nodes) {
  let ids = []
  function traverse(node) {
    ids.push(node.data.id)
    if (node.children && node.children.length > 0) {
      node.children.forEach(child => traverse(child))
    }
  }
  nodes.forEach(node => traverse(node))
  return ids
}

const handleParams = () => {
  const params = {
    task_id: search.originTaskId ? [search.originTaskId] : [],
    category:
      search.category.length === 1 && search.category[0] === 0
        ? []
        : getAllIds(
            questionTypes.value.filter(item =>
              search.category.includes(item.data.id)
            )
          )
  }
  if (search.high_rate !== 100 || search.low_rate !== 0) {
    params.score_rate_interval = {
      max: search.high_rate / 100,
      min: search.low_rate / 100
    }
  }
  return params
}
const refreshList = () => {
  emits('refresh-common-list', handleParams())
}

watch(
  () => [
    search.category,
    search.high_rate,
    search.low_rate,
    knowledgeStore.selectedStudent
  ],
  () => {
    refreshList()
  },
  {
    deep: true
  }
)

// 作答记录
const drawerVisible = ref(false)
const currentRecord = ref()
const showRecord = (record, question) => {
  currentRecord.value = record
  currentRecord.value.question = question
  drawerVisible.value = true
}

const getColor = (originScore, score) => {
  if (score === 0) {
    return '#FF6D65'
  } else if (score >= originScore) {
    return '#4EC680'
  } else {
    return '#FBC25E'
  }
}

const getRecordAnswer = (item, answer, id) => {
  const from = Number(id.split('-')[0])
  if (!answer || !item || (from !== 4 && from !== 2)) return
  let res = ''
  switch (item.type) {
    case 1:
      res = String.fromCharCode(65 + Number(answer))
      break
    case 2:
      res = (answer || [])
        .map(item => String.fromCharCode(65 + Number(item)))
        .join('')
      break
    case 36:
      res = answer[0] ? (answer[0] === '0' ? '对' : '错') : ''
      break
  }
  return res
}

// 获取举一反三题目
const getPushingQuestion = async () => {
  const params = commonList.value.map(item => {
    return {
      question_id: item.question.id,
      kpoint_ids: (item.question.keypoint || []).map(item => item.id),
      question_type: item.question.type,
      filter_para: {
        duplicate_id_list: [item.question.id]
      }
    }
  })
  const { code, data, msg } = await getJyfsQustions({
    analogue_request_list: params,
    check_other_source: 1
  })
  if (code === 10000) {
    const list = data?.analgoue_question_list || []
    for (let index = 0; index < list.length; index++) {
      const element = list[index]
      commonList.value[index].pushingList = (element?.analogue_questions || [])
        .slice(0, 3)
        .map(item => {
          return {
            showTopicParser: false,
            loading: false,
            isSelected: true,
            question: item
          }
        })
    }
  } else {
    ElMessage.error(msg || '发生错误')
  }
}

// 是否选入举一反三的题目
const selectQuestion = (originIndex, index) => {
  commonList.value[originIndex].pushingList[index].isSelected =
    !commonList.value[originIndex].pushingList[index].isSelected
}

// 将举一反三的题目加入试题篮
const saveSimilarQuestion = () => {
  const list = []
  commonList.value.forEach(item1 => {
    item1.pushingList.forEach(item2 => {
      if (item2.isSelected) {
        const params = {
          topic_id: item2.question.id,
          source: 2,
          topic_type: item2.question.type,
          subject_id: item2.question.subject,
          question_detail: item2.question,
          relation_id: item1.question.id,
          is_similar: 0
        }
        list.push(params)
      }
    })
  })
  taskStore.setTaskList(list, true)
  let url = router.resolve({
    name: 'taskDetail'
  })
  setTimeout(() => {
    emits('close-pushing')
    window.open(url.href, '_blank')
  }, 200)
}

watch(
  () => taskStore.taskList.length,
  val => {
    if (props.isPushing && val && commonList.value.length) {
      commonList.value = commonList.value.filter(item =>
        taskStore.taskList.find(item1 => item1.topic_id === item.question.id)
      )
    }
  },
  {
    deep: true
  }
)

// 试题蓝于共性错题公共题目
const loading = ref(false)
const commonList = ref([])
watch(
  () => props.isPushing,
  async val => {
    commonList.value = []
    if (val) {
      resetCommonList()
      loading.value = true
      await getPushingQuestion()
      loading.value = false
    }
  }
)

watch(
  () => commonList.value.length,
  val => {
    if (!val) {
      emits('close-pushing')
    }
  }
)

const resetCommonList = () => {
  commonList.value = []
  for (let index = 0; index < taskStore.taskList.length; index++) {
    const element = taskStore.taskList[index]
    const res = topicList.value.find(
      item1 => item1.question.id === element.topic_id
    )
    if (res) {
      commonList.value.push(res)
    }
  }
}

const renderList = computed(() => {
  return props.isPushing ? commonList.value : topicList.value
})

const switchJyfsQuestionAna = (originIndex, index) => {
  commonList.value[originIndex].pushingList[index].showTopicParser =
    !commonList.value[originIndex].pushingList[index].showTopicParser
}

// 换一道
/* eslint-enable */
const switchAnother = async (question, originIndex, index) => {
  const current = question.question
  question.showTopicParser = false
  commonList.value[originIndex].pushingList[index].loading = true
  const { code, data } = await getXkwSimilarQuestions(current.id, {
    kpoint_ids: current.keypoint.map(item => item.id),
    content: current.content,
    count: 1
  })
  if (code === 10000 && !data?.questions) {
    ElMessage.warning('暂无推荐题目！')
  } else if (data.questions) {
    commonList.value[originIndex].pushingList[index].showTopicParser = false
    commonList.value[originIndex].pushingList[index].question =
      data.questions[0]
  }
  commonList.value[originIndex].pushingList[index].loading = false
}

onMounted(() => {
  getQuestionTypeFn()
})
</script>
<!-- eslint-disable -->
<style lang="less">
.right-rate-popover {
  width: fit-content !important;
  display: flex;
  flex-direction: column;
  gap: 20px;

  .right-rate {
    .name {
      color: #040b1a;
      margin-bottom: 8px;
    }

    .separator {
      color: #b7b8bb;
    }

    .input-box {
      display: flex;
      gap: 4px;
      align-items: center;

      .el-input-number {
        width: 64px;
        height: 32px;

        :deep(.el-input__wrapper) {
          border-radius: 0;
          border-left: unset;
          border-right: unset;
          box-shadow: none;
        }
      }
    }
  }
}

.answer-record-popover {
  width: 180px !important;
  .record-list {
    margin-bottom: 0 !important;
    display: flex;
    flex-direction: column;
    gap: 10px;
    width: fit-content;

    .list-item {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}
</style>
<style lang="less" scoped>
.common-wrong-search {
  display: flex;
  align-items: center;
  margin-bottom: 10px;

  .selected-student {
    height: 40px;
    border: 1px solid #cdced1;
    padding: 0 17px;
    border-radius: 3px;
    font-size: 16px;
    display: flex;
    align-items: center;
    margin-right: 24px;
  }

  .total {
    color: @color-brand-regular;
  }

  .type-select {
    width: 200px;
    height: 40px;
    margin-right: 24px;

    :deep(.el-select__wrapper) {
      box-shadow: unset;
      border: 1px solid #cdced1;
      height: 40px;
      padding: 0 17px;
      border-radius: 3px;
      font-size: 16px;

      .el-tag {
        background-color: #f8fafd;
        color: #4f545f;
        border-radius: 0;
        font-size: 14px;
        align-items: center;
      }
    }
  }

  label,
  .title-wrap {
    height: 40px;
    border: 1px solid #cdced1;
    padding: 0 17px;
    border-radius: 3px;
    display: inline-flex;
    align-items: center;
    margin-right: 24px;
    color: #4f545f;

    .icon {
      cursor: pointer;
      margin-left: 8px;
    }
  }

  .title {
    &-wrap {
      border-color: @color-brand-regular;
      color: @color-brand-regular;

      .name {
        max-width: 240px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .search-wrapper {
    display: flex;
    align-items: center;
  }
}

.generality-topic-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;

  :deep(.el-drawer) {
    &__title {
      font-size: 20px;
      font-weight: 500;
      color: #040b1a !important;
    }

    &__header {
      margin-bottom: 0;
    }
  }
  .record-drawer {
    .record {
      &-item {
        border-bottom: 1px solid @color-neutral-line-border;
        margin-bottom: 10px;
        padding-bottom: 10px;

        .info {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;

          .score {
            margin-left: 10px;
          }
        }
      }
    }
  }
}

.generality-topic {
  flex: 1;
  overflow-y: auto;

  --topic-x-padding: 20px;
  --topic-y-padding: 12px;
  --render-radius: 8px;

  :deep(.topic-cpn) {
    padding: var(--topic-y-padding) 0 0;
    border: 1px solid #c4c4c4;
    border-radius: var(--render-radius);
    margin-bottom: 14px;
    overflow: hidden;

    &.jyfs-question {
      border-color: #d89b25;
    }

    .rb-question {
      padding: 0 var(--topic-x-padding);
      margin: 0 auto;
    }

    :deep(.expand-analysis-item) {
      width: 94%;
      margin: 0 auto;
    }
  }

  .topic-head {
    display: flex;
    align-items: center;
    margin-bottom: var(--topic-y-padding);
    border-bottom: 1px solid rgba(196, 196, 196, 0.3);
    color: #999;
    font-size: 16px;
    padding-bottom: var(--topic-y-padding);
    padding-left: var(--topic-x-padding);

    .label-arr {
      display: flex;
      align-items: center;

      .label {
        font-size: 16px;
        color: #040b1a;
        opacity: 0.5;

        &.jyfs-label {
          background-color: #fff6e1;
          padding: 5px 14px;
          border: 1px solid #d89b25;
          color: #d89b25;
          font-weight: 700;
          opacity: 1;
          border-radius: 5px;
        }
      }

      .divide {
        height: 16px;
        margin: 0 16px;
        width: 1px;
        background-color: #040b1a;
        opacity: 0.5;
      }
    }
  }

  .topic-foot {
    .knowledge {
      padding: var(--topic-y-padding) var(--topic-x-padding);
      color: #040b1a;
      font-size: 16px;
      border-bottom: 1px solid rgba(196, 196, 196, 0.3);

      .knowledge-name {
        display: inline-flex;
        align-items: center;
        max-width: 100%;
        height: 27px;
        padding: 0 6px;
        border: 1px solid #e1e1e1;
        border-radius: 3px;
        background-color: #fbfbfb;
        color: #616161;
        font-size: 14px;
        line-height: 27px;
        cursor: pointer;
        margin-right: 8px;
      }
    }

    .more {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: var(--topic-y-padding) var(--topic-x-padding);

      &.flex-end {
        justify-content: flex-end;
      }

      .statistics-tip {
        color: @theme-color;
        opacity: 0.7;
        user-select: none;
        cursor: pointer;
        font-size: 14px;
        display: flex;
        gap: 15px;
        align-items: center;

        .expanded {
          transform: rotate(90deg);
          transition: 0.3s;
        }
      }

      .btn-group {
        display: flex;
        flex-direction: row-reverse;
        gap: 30px;
      }

      .text-btn {
        color: @theme-color;
        border: unset;
        background: unset;
        cursor: pointer;
        font-size: 14px;
      }

      .action-btn {
        cursor: pointer;
        color: gray;
        font-size: 14px;
        line-height: 14px;
        display: inline-flex;
        align-items: center;

        .icon {
          margin-right: 4px;
        }

        .analysis-icon {
          display: inline-block;
          width: 14px;
          height: 14px;
          line-height: 14px;
          background: url(@/assets/images/assignment/analysis-icon.png)
            no-repeat center/cover;
        }
      }

      .basket-btn {
        padding: 2px 16px;
        font-size: 14px;
        cursor: pointer;
        background: #bfd9ff;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #bfd9ff;
        color: #448efb;
        &:hover {
          opacity: 0.95;
        }

        &.disabled {
          cursor: not-allowed;
          opacity: 0.5;
        }

        &.remove-btn {
          border-radius: 4px 4px 4px 4px;
          border: 1px solid #448efb;
          color: #448efb;
          background: #fff;
        }
      }
    }

    .statistics {
      padding: var(--topic-y-padding) var(--topic-x-padding) 0
        var(--topic-x-padding);
    }
  }

  .record-tip {
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 14px;
  }

  .expand-box {
    margin-top: --topic-y-padding;
    padding: 20px;
    align-items: self-start;
    background-color: #f8fafd;
    .process-box {
      min-height: 100px;
      width: 400px;
      border-right: 1px solid #dce2ef;
    }
    .student-box {
      flex: 1;
      gap: 20px;
      padding: 20px;

      .index-img {
        width: 24px;
        margin-bottom: 2px;
      }
      .correct-answer {
        color: #4ec680;
      }
      .student-list {
        flex-wrap: wrap;
        margin: 4px 0 16px;
        gap: 12px;
        .student-item {
          padding: 4px;
          border: #dce1ef 1px solid;
          .student-name {
            margin-right: 2px;
            max-width: 80px;
          }
        }
      }
    }
  }
}

.btn-box {
  padding-right: 24px;
  display: flex;
  justify-content: flex-end;

  .btn {
    width: 88px;
    height: 32px;
    border: 1px solid;
    border-radius: 3px;
    font-size: 16px;
  }

  .save-btn {
    background-color: @color-brand-regular;
    color: #fff;
    margin-left: 16px;

    &:hover {
      background-color: @color-brand-checked;
    }
  }

  .cancel-btn {
    color: @color-brand-regular;
    background-color: #fff;
    border-color: @color-brand-regular;

    &:hover {
      background-color: #ecf5ff;
    }
  }
}
</style>
